/*

heping
Node.js
用于复制一个文件夹下的文件到另一个文件夹

*/
const Def = {
  // rootDir: __dirname,
  rootDir: 'F:\\Workload\\Iot\\gitee\\iot-devops-portal-system',
  targetDir: 'F:\\Test\\新建文件夹\\目标文件夹',
  excludeFile: [],
  excludeDir: [
    '.git',
    'node_modules'
  ]
}

const fs = require('fs')
const path = require('path')

function _copy(rootDir, parentDir) {
  if (!fs.existsSync(rootDir) || !fs.existsSync(Def.targetDir)) {
    return
  }

  fs.readdirSync(rootDir).map(dir => (
    {
      fileName: dir,
      filePath: `${rootDir}\\${dir}`,
      parentDir: parentDir ? `${parentDir}\\${dir}` : dir
    }
  )).forEach(({ fileName, filePath, parentDir }) => {
    if (!fs.existsSync(filePath)) {
      return
    }
    const statInfo = fs.lstatSync(filePath)
    if (statInfo.isFile()) {
      const prevDirs = parentDir.split('\\')
      prevDirs.pop()
      prevDirs.map((dir, index) => prevDirs.slice(0, index + 1).join('\\')).forEach(dir => {
        const targetDir = `${Def.targetDir}\\${dir}`
        if (!fs.existsSync(targetDir)) {
          fs.mkdirSync(targetDir, { recursive: true })
        }
      })

      fs.createReadStream(filePath).pipe(
        fs.createWriteStream(`${Def.targetDir}\\${parentDir}`)
      )
    } else if (statInfo.isDirectory() && !Def.excludeDir.some(v => v === fileName)) {
      _copy(filePath, parentDir)
    }
  })
}
_copy(Def.rootDir)